from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import cv2
from PIL import Image
import os
import ctypes
import abc
import importlib

import shutil
import threading
import time,requests
from lib.pconf import Config, sys_cfg

lib_input_op = ctypes.cdll.LoadLibrary

class BarStatusWorker(QThread):
    progressBarValue = pyqtSignal(int)

    def __init__(self,):
        super(BarStatusWorker, self).__init__()
        self.flag = True

    def run(self):
        self.flag = True
        self.progressBarValue.emit(0)

        fn_status = os.path.join(sys_cfg["system_rootpath"], 'train_data/bar_status.txt')
        while self.flag:
            time.sleep(1)
            if os.path.exists(fn_status):
                f = open(fn_status)
                curr, total = f.readlines()[0].strip().split()
                f.close()

                BarValue = int(curr) / int(total) * 100
                self.progressBarValue.emit(BarValue)

    def stop(self):
        self.flag = False
        self.progressBarValue.emit(100)
        time.sleep(0.1)

class BaseDetector(metaclass=abc.ABCMeta):
    def __init__(self, cfg):
        self.cfg = cfg
        self.barvalue = None
        self.pbar = None

        self.tmp_path = os.path.join(cfg["system_rootpath"], cfg['tmp']['root_path'])
        self.train_data_path = os.path.join(cfg["system_rootpath"], cfg['train']['root_path'])

    def create_dir(self, path):
        def deletetmp(path):
            if os.path.exists(path):
                shutil.rmtree(path, True)

        threads = []
        for i in range(10):
            t = threading.Thread(target=deletetmp, args=(path,))
            threads.append(t)
            t.start()
        for t in threads:
            t.join()
        os.makedirs(path)


    @abc.abstractmethod
    def train(self):
        pass

    @abc.abstractmethod
    def inference(self):
        pass

class ChangeDetector(QThread):
    trigger = pyqtSignal()

    def __init__(self, cfg, text, runType="Train", pbar=None, barvalue=None):
        super(ChangeDetector, self).__init__()
        self.pbar = pbar
        self.barvalue = barvalue
        self.runType = runType
        self.cfg = cfg

    def str2Hump(self, text):
        arr = filter(None, text.lower().split('_'))
        res = ''
        j = 0
        for i in arr:
            if j == 0:
                res = i[0].upper() + i[1:]
            else:
                res = res + i[0].upper() + i[1:]
            j += 1
        return res


    def run(self) -> None:
        if self.runType == 'Train':
            url = sys_cfg["train_image_url"]
            imageFilePath01 = sys_cfg["change_baseimg_path"]
            imageFileName01 = os.path.split(imageFilePath01.strip())[1]
            imageFilePath02 = self.cfg['img_path']
            print(imageFilePath02)
            imageFileName02 = os.path.split(imageFilePath02.strip())[1]


            filenames = [imageFilePath01 , imageFilePath02]
            for filename in filenames :
                image = Image.open(filename).convert('RGB')
                image.save(filename)

            label_name = imageFileName02.replace(".jpg", ".json")

            file_dict = {
                'img01' : (imageFileName01 ,
                           open(imageFilePath01 , 'rb') ,
                           'image/jpg') ,
                'img02' : (imageFileName02 ,
                           open(imageFilePath02 , 'rb') ,
                           'image/jpg') ,
                "label" : (label_name,
                           open((os.path.join(sys_cfg['project_path'] , label_name)), 'rb')
                           )
            }

            result = requests.post(url , files=file_dict)

            img = result.content  # mp3二进制数据

            # 将img的二进制数据保存到本地的img
            f = open(os.path.join(sys_cfg['project_path'] , "detectedImg.jpg") , "wb")
            f.write(img)
            f.close()

            # resize
            image_in = cv2.imread(imageFilePath02)
            image_out = cv2.imread(os.path.join(sys_cfg['project_path'] , "detectedImg.jpg"))
            image_resized = cv2.resize(image_out , (image_in.shape[1] , image_in.shape[0]))
            cv2.imwrite(os.path.join(sys_cfg['project_path'] , "resizedDetectedImg.jpg") , image_resized)

        elif self.runType == 'Inference':
            url = sys_cfg["sent_image_url"]
            imageFilePath01 = sys_cfg["change_baseimg_path"]
            print(imageFilePath01)
            imageFileName01 = os.path.split(imageFilePath01.strip())[1]
            imageFilePath02 = self.cfg['img_path']
            print(imageFilePath02)
            imageFileName02 = os.path.split(imageFilePath02.strip())[1]

            filenames = [imageFilePath01, imageFilePath02]
            for filename in filenames :
                image = Image.open(filename).convert('RGB')
                image.save(filename)

            file_dict = {
                'img01' : (imageFileName01 ,
                           open(imageFilePath01 , 'rb') ,
                           'image/jpg') ,
                'img02' : (imageFileName02 ,
                           open(imageFilePath02 , 'rb') ,
                           'image/jpg') ,
            }
            result = requests.post(url , files=file_dict)
            print(dir(result))
            print(dir(result.content))

            img = result.content  # mp3二进制数据

            # 将img的二进制数据保存到本地的img
            f = open(os.path.join(sys_cfg['project_path'] , "detectedImg.jpg") , "wb")
            f.write(img)
            f.close()

            # resize
            image_in = cv2.imread(imageFilePath02)
            image_out = cv2.imread(os.path.join(sys_cfg['project_path'] , "detectedImg.jpg"))
            image_resized = cv2.resize(image_out , (image_in.shape[1] , image_in.shape[0]))
            cv2.imwrite(os.path.join(sys_cfg['project_path'] , "resizedDetectedImg.jpg") , image_resized)

        print('over')
        self.trigger.emit()





